package com.jxwifi.cloud.quickcleanserver.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.HuaWeiRegister;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.alibaba.sdk.android.push.register.OppoRegister;
import com.bumptech.glide.Glide;
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader;
import com.bumptech.glide.load.model.GlideUrl;
import com.idroid.async.AsyncWorker;
import com.idroid.utils.ListDataSave;
import com.jxwifi.cloud.quickcleanserver.bean.HeadBean;
import com.jxwifi.cloud.quickcleanserver.okhttp.AuzHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.LongTimeAuzHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.OkHttp;
import com.jxwifi.cloud.quickcleanserver.upgrade.UpgradeCodeName;
import com.jxwifi.cloud.quickcleanserver.utils.LocationGaoDe;
import com.jxwifi.cloud.quickcleanserver.utils.MyActivityManager;
import com.jxwifi.cloud.quickcleanserver.utils.OkHttpInterceptor;
import com.jxwifi.cloud.quickcleanserver.utils.UUIDS;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import cn.trinea.android.common.util.PackageUtils;
import cn.trinea.android.common.util.PreferencesUtils;
import okhttp3.Cache;

/**
 * Created by Administrator on 2019/5/11.
 */

public class CleaningApplication extends Application {

    private static final String TAG = "OSH";
    private static String QR_CODE_BEAN = "QR_CODE_ID";
    private ListDataSave dataSave;
    private CloudPushService pushService;

    public static final String APPCATION_NAME = "com.jxwifi.cloud.quickcleanserver";
    public static final String SCRREN_HEIGHT = "scrren_height";
    public static int JUMP_TYPE = 100;//这个字段用于处理回到首页时的区分操作
    final String DEFAULT_RES_PATH_FREFIX = "android.resource://";
    final String DEFAULT_RES_SOUND_TYPE = "raw";
    final String ASSIGN_NOTIFCE_SOUND = "alicloud_notification_sound_assign";

    @Override
    public void onCreate() {
        super.onCreate();
        initCloudChannel(getApplicationContext());
        if (APPCATION_NAME.equals(getAppName())) { //防止独立进程的服务启动造成onCreate()执行多次
            dataSave = new ListDataSave(getApplicationContext(), QR_CODE_BEAN);
            saveScreen();
            //友盟统计代码
            UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE,"");
            UMConfigure.setLogEnabled(true);//日志输出
            MobclickAgent.setCatchUncaughtExceptions(true);//捕获错误信息
            OkHttp.version = UpgradeCodeName.getVerName(getApplicationContext());//获取软件版本号
            UUIDS.buidleID(this).check();
            registerActivityManger();//注册Activity生命周期回调
            new LocationGaoDe().init(getApplicationContext());
            LocationGaoDe.startLocation();
            //APP中保存的DEVICE_ID 用于阿里云推送的一个ID
            SharedPreferences sharedPreferences = getSharedPreferences(QR_CODE_BEAN,
                    Activity.MODE_PRIVATE);
            String strJson = sharedPreferences.getString(QR_CODE_BEAN, null);
            List<HeadBean> mListBean = JSON.parseArray(strJson, HeadBean.class);
            if (mListBean != null) {
                Log.w("OSH", "KJB_DEVICE_ID=" + mListBean.get(0).getDeviceId());
                OkHttp.Deviceid(mListBean.get(0).getDeviceId());
            }
            if (AccountMgr.isLogin(getApplicationContext())) {
                AuzHttp.KJB_APP_Token = AccountMgr.gettoken(getApplicationContext());
            }

            AsyncWorker.execute(new Runnable() {
                @Override
                public void run() {
                    OkHttp.addInterceptor(new OkHttpInterceptor(PackageUtils.getLocalVersionName
                            (getApplicationContext())));
                    OkHttp.setCache(new Cache(new File(getExternalCacheDir(), "kjb_cleaning"), 50 * 1024 * 1024));
                  /* Glide网络方式直接使用okhttp库*/
                    Glide.get(getApplicationContext()).register(GlideUrl.class, InputStream.class, new
                            OkHttpUrlLoader.Factory(LongTimeAuzHttp.longTimeOkHttpClient));
                    //初始化本地文本数据现在没有用到可先注销
                    // LocalDataUtil.initAll(getApplicationContext());
                }
            });
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }


    private String getAppName() {
        String processName = null;
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == android.os.Process.myPid()) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
            }
        }
        return processName;
    }
    /**
     * 存储屏幕宽度
     */
    private void saveScreen() {
        WindowManager wm = (WindowManager) this.getSystemService(WINDOW_SERVICE);
        PreferencesUtils.putInt(getApplicationContext(), SCRREN_HEIGHT, wm.getDefaultDisplay().getHeight());
    }

    private void registerActivityManger() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {
                //记录当前活动的Activity
                MyActivityManager.getInstance().setCurrentActivity(activity);
            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

    private void initCloudChannel(final Context applicationContext) {
        try{
            PushServiceFactory.init(applicationContext);
        }catch (Exception e) {
            e.printStackTrace();
        }
        pushService = PushServiceFactory.getCloudPushService();
        CloudChannel();
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                if (!TextUtils.isEmpty(PushServiceFactory.getCloudPushService().getDeviceId())) {
                    List<HeadBean> mListBean = new ArrayList<HeadBean>();
                    HeadBean headBean = new HeadBean();
                    headBean.setDeviceId(PushServiceFactory.getCloudPushService().getDeviceId());
                    mListBean.add(headBean);
                    dataSave.setDataList(QR_CODE_BEAN, mListBean);
                    if (!TextUtils.isEmpty(PushServiceFactory.getCloudPushService().getDeviceId())) {
                        OkHttp.Deviceid(mListBean.get(0).getDeviceId());
                    }
                }
            }

            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Log.w(TAG, "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });

        // 注册方法会自动判断是否支持小米系统推送，如不支持会跳过注册。
        MiPushRegister.register(applicationContext, " 2882303761517857473", "5251785714473");
        // 注册方法会自动判断是否支持华为系统推送，如不支持会跳过注册。
        HuaWeiRegister.register(applicationContext);
        // OPPO通道注册
        OppoRegister.register(applicationContext, "79LF3754jh4wcgSgggwGoo0KG", "6dc32e197affE08A692d7d51336345dD"); // appKey/appSecret在OPPO通道开发者平台获
    }

    // 注册NotificationChannel
    public void CloudChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //系统大于8.0或以上的自定义通知栏提示，小于8.0的用阿里云自带通知栏
            Log.w(TAG, "setNotificationSoundFilePath  O");
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            // 通知渠道的id
            String id = "kjb";
            // 用户可以看到的通知渠道的名字
            CharSequence name = "notification channel";
            // 用户可以看到的通知渠道的描述
            String description = "notification description";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(id, name, importance);
            // 配置通知渠道的属性
            mChannel.setDescription(description);
            // 设置通知出现时的闪灯（如果 android 设备支持的话）
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            // 设置通知出现时的震动（如果 android 设备支持的话）
            mChannel.enableVibration(true);
            mChannel.setBypassDnd(true);//设置是否绕过免打扰模式
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mChannel.setSound(Uri.parse(DEFAULT_RES_PATH_FREFIX + getPackageName() + "/"
                    + getResources().getIdentifier(ASSIGN_NOTIFCE_SOUND, DEFAULT_RES_SOUND_TYPE, getPackageName())), Notification.AUDIO_ATTRIBUTES_DEFAULT);
            //最后在notificationmanager中创建该通知渠道
            mNotificationManager.createNotificationChannel(mChannel);
        } else {
            int assignSoundId = getResources().getIdentifier(ASSIGN_NOTIFCE_SOUND, DEFAULT_RES_SOUND_TYPE, getPackageName());
            if (assignSoundId != 0) {
                String defaultSoundPath = DEFAULT_RES_PATH_FREFIX + getPackageName() + "/" + assignSoundId;
                pushService.setNotificationSoundFilePath(defaultSoundPath);
                Log.w(TAG, "setNotificationSoundFilePath  true");
            } else {
                Log.w(TAG, "setNotificationSoundFilePath  false");
            }
        }
    }

}
